//
//  LoginVC.m
//  K-Music
//
//  Created by CHUN on 15/12/27.
//  Copyright © 2015年 CHUN. All rights reserved.
//

#import "LoginVC.h"
#import "RegisteredVC.h"
#import "Forgot_password.h"
#import "AppDelegate.h"


@interface LoginVC ()<UITextFieldDelegate,UIAlertViewDelegate>
{
    UITextField * _texfiled1;
    UITextField * _texfiled2;
}
@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登陆";
    
    self.view.backgroundColor = RGB(241, 242, 244);
    
    //左边按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(back_back)];
    
    [self tapView];
    
    [self createUI];
    
}

- (void)back_back
{
    NSLog(@"login 返回默认选择的第二个");
    [self dismissViewControllerAnimated:YES completion:^(){

        
    }];
}

-(void)createUI
{
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 10, WIDTH, 100)];
    
    view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:view];
    
    UILabel *lable = [UILabel lableWithText:CGRectMake(WIDTH/16, 5, 80, 40) Color:RGB(4, 4, 4) Text:@"手机号" Font:nil];
    [view addSubview:lable];
    
    _texfiled1 = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lable.frame), 5, WIDTH*0.75, 40) ];
    _texfiled1.borderStyle = UITextBorderStyleNone;
    _texfiled1.placeholder = @"手机号/K歌号";
    _texfiled1.delegate = self;
    [view addSubview:_texfiled1];
    
    UIView * bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 50, WIDTH, 1)];
    bgview.backgroundColor = RGB(241, 242, 244);
    [view addSubview:bgview];
    
    UILabel *lable_code = [UILabel lableWithText:CGRectMake(WIDTH/16, 55, 80, 40) Color:RGB(4, 4, 4) Text:@"登陆密码" Font:nil];
    [view addSubview:lable_code];
    
    _texfiled2 = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lable_code.frame), 55, WIDTH*0.75, 40) ];
    _texfiled2.borderStyle = UITextBorderStyleNone;
    _texfiled2.placeholder = @"登陆密码";
    _texfiled2.secureTextEntry = YES;
    _texfiled2.delegate = self;
    [view addSubview:_texfiled2];
    
    UILabel * registered_L = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH/16, CGRectGetMaxY(view.frame) + 5 , WIDTH/4, 30)];
    registered_L.userInteractionEnabled=YES;
    registered_L.font=[UIFont systemFontOfSize:15];
    registered_L.textAlignment = UITextAlignmentLeft;
    registered_L.text = @"注册";
    registered_L.textColor = [UIColor orangeColor];
    
    UIButton * registered_button = [MyToolsClass createBtnWithFrame:CGRectMake(0, 0 , WIDTH/4, 30) title:nil image:nil target:self action:@selector(registered_button)];
    registered_button.layer.cornerRadius = 5;
    registered_button.clipsToBounds = YES;
    [registered_L addSubview:registered_button];
    [self.view addSubview:registered_L];
    
    UILabel * forgot_password_L = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - WIDTH/4, CGRectGetMaxY(view.frame) + 5 , WIDTH/4, 30)];
    forgot_password_L.userInteractionEnabled=YES;
    forgot_password_L.font=[UIFont systemFontOfSize:15];
    forgot_password_L.text = @"忘记密码 ?";
    forgot_password_L.textColor = [UIColor orangeColor];
    
    UIButton * forgot_password_B = [MyToolsClass createBtnWithFrame:CGRectMake(0, 0 , WIDTH/4, 30) title:nil image:nil target:self action:@selector(Forgot_button)];
    forgot_password_B.layer.cornerRadius = 5;
    forgot_password_B.clipsToBounds = YES;
    [forgot_password_L addSubview:forgot_password_B];
    [self.view addSubview:forgot_password_L];
    
    UIButton * login_button = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH/32, CGRectGetMaxY(forgot_password_L.frame) +10,WIDTH-WIDTH/16, WIDTH/10)];
    
    [login_button addTarget:self action:@selector(login_button) forControlEvents:UIControlEventTouchUpInside];
    [login_button setTitle:@"登陆" forState:UIControlStateNormal];
    login_button.layer.cornerRadius = 5;
    login_button.clipsToBounds = YES;
    login_button.backgroundColor = RGB(240, 176, 39);
    
    [self.view addSubview:login_button];
    
}

- (void)registered_button
{
    [self.navigationController pushViewController:[RegisteredVC new] animated:YES];
}

- (void)Forgot_button
{
    [self.navigationController pushViewController:[Forgot_password new] animated:YES];
}

- (void)login_button
{
    NSLog(@"登陆");
    
    if ([RegularTools validateMobile:_texfiled1.text]== 0 || _texfiled2.text.length == 0)
    {
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示"message:@"手机号码或密码错误，请重新输入" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [myAlertView show];
    }
    else
    {
        [self login_login];
    }
}

- (void)login_login
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer  = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/login"];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSDictionary * login = @{@"username":_texfiled1.text,@"password":_texfiled2.text};
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Content-Type"];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    
    [manager POST:intactURL parameters:login success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary * result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         
         NSLog(@"================:%@",result);
         NSString * resultCode = result[@"resultCode"];
         
         if ([resultCode isEqual:@"SUCCESS"]) {
             
             NSDictionary * body = result[@"body"] ;
             
             [FileStorage NSUserDefault_setObject:body[@"access_token"] forKey:access_token];
             
             [self get_user_account];
             
         }
         else
         {
             NSLog(@"%@",[result objectForKey:@"description"]);
             [MBProgressHUD showErrorWithStatus:@"请求失败" toView:self.view];
         }
         
     }failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"%@", error);
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"输入错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
         [alert show];
         
     }];
    
}

#pragma mark -获取个人重要信息-
- (void)get_user_account
{
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/users/current_user?page=0&size=20&sort=createdDate,DESC"];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"成功GET个人信息 --> %@", dic);
        NSDictionary * userDetail = [[dic objectForKey:@"body"] objectForKey:@"userDetail"];
        NSLog(@"%@",userDetail);
        
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"id"] forKey:User_id];
        
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"nickName"] forKey:nickName];
        
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"phone"] forKey:user_phone];
        
        
        if(strIsEmpty([userDetail objectForKey:@"avatar"]))
        {
            [FileStorage NSUserDefault_setObject:@"001" forKey:user_image];
        }
        else
        {
            [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"avatar"] forKey:user_image];
        }
        
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"goldCoin"] forKey:user_goldCoin];
        
        if(strIsEmpty([userDetail objectForKey:@"income"]))
        {
            [FileStorage NSUserDefault_setObject:@"0" forKey:user_income];
        }
        
        //财富等级
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"fortuneLevelDesc"] forKey:fortuneLevelDesc];
        
        //财富图片
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"fortuneLevelIcon"] forKey:fortuneLevelIcon];
        
        //歌手等级
        [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"singerLevelDesc"] forKey:singerLevelDesc];
        
        //歌手等级图片
        if(strIsEmpty([userDetail objectForKey:@"singerLevelIcon"]))
        {
            [FileStorage NSUserDefault_setObject:@"0" forKey:singerLevelIcon];
        }
        else
        {
            [FileStorage NSUserDefault_setObject:[userDetail objectForKey:@"singerLevelIcon"] forKey:singerLevelIcon];
        }
        
        [FileStorage NSUserDefault_getObjectForKey:nickName];
        
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [delegate initVC];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
        [MBProgressHUD showErrorWithStatus:@"个人信息获取失败" toView:self.view];
        
    }];
}

//收键盘手势
- (void)tapView
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(CancelkeyBoard)];
    [self.view addGestureRecognizer:tap];
}

- (void)CancelkeyBoard
{
    [ _texfiled1 resignFirstResponder];
    
    [ _texfiled2 resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 {
 address = "<null>";
 avatar = "http://7xp1hi.com1.z0.glb.clouddn.com/cat.jpg";
 birthday = "<null>";
 consumedNumber = 0;
 consumedNumberMonthly = 0;
 createdBy = system;
 createdDate = "2015-12-09T02:57:28Z";
 email = "<null>";
 fanNumber = 4;
 fanNumberMonthly = 0;
 followed = "<null>";
 fortuneLevel = 0;
 fortuneLevelDesc = "\U8d2b\U519c";
 fortuneLevelIcon = "http://7xp1hi.com2.z0.glb.qiniucdn.com/ogbuY8zg3JEjHrxVFQhmXP.png";
 goldCoin = 0;
 id = 10009;
 income = "<null>";
 isVIP = "<null>";
 isVip = "<null>";
 lastModifiedBy = 3;
 lastModifiedDate = "2016-01-16T06:57:01Z";
 latitude = "23.11705530622489";
 longitude = "113.2759952545166";
 nickName = 18888888888;
 popularity = 7;
 roomSetting = "<null>";
 signature = "\U9519\U8fc7\U592a\U591a\U7684\U4eba\Uff0c\U9519\U8fc7\U592a\U591a\U7684\U4e8b";
 singerLevel = 0;
 singerLevelDesc = "\U65b0\U4eba";
 singerLevelIcon = "<null>";
 status = "<null>";
 userId = 10009;
 }
 
 */



@end
